<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入内容" clearable>
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="openRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="roleList" border stripe style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <pre>{{ scope.row }}</pre>
          </template>
        </el-table-column>

        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column prop="roleName" label="角色" width="180">
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="180">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" @click="roleMenuDialog(scope.row.id)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="query.current"
                     :page-size="query.size" :total="total" :page-sizes="[1, 2, 3, 50]"
                     layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>

    </el-card>

    <!--      分配权限-->
    <el-dialog :close-on-click-modal="false"
               title="分配权限" @close="resetDefaultKeys"
               :visible.sync="roleMenuFlag" width="30%">

      <el-tree :data="allMenus" :props="allMenusProps" node-key="id"
               show-checkbox default-expand-all highlight-current
               :default-checked-keys="defaultKeys" ref="treeRef">
      </el-tree>
      <span slot="footer">
        <el-button type="primary" @click="editUserMenus">确 定</el-button>
        <el-button @click="closeUserMenus">取 消</el-button>
      </span>
    </el-dialog>

    <!--      添加角色-->
    <el-dialog :close-on-click-modal="false"
               title="添加角色" @close="closeRoleDialog"
               :visible.sync="openRoleFlag" width="30%">
      <el-form :model="addRoleForm" :rules="addRoleFormRule" ref="addRoleFormRef"
               status-icon
               label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="addRoleForm.roleName"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="addRoleForm.remark" type="textarea"></el-input>
        </el-form-item>

      </el-form>

      <span slot="footer">
        <el-button type="primary" @click="addRole">确 定</el-button>
        <el-button @click="openRoleFlag = false">取 消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'UserPermission',
  data () {
    return {
      query: {
        roleName: '',
        current: 1,
        size: 2
      },
      total: 0,
      addRoleForm: {
        roleName: '',
        remark: ''
      },
      roleList: [],
      allMenus: [],
      defaultKeys: [],
      roleMenuFlag: false,
      openRoleFlag: false,
      roleId: '',
      allMenusProps: {
        children: 'items',
        label: 'menuName'
      },

      addRoleFormRule: {
        roleName: [{
          required: true,
          message: '角色名称必填',
          trigger: 'blur'
        }]
      }
    }
  },
  created () {
    this.getRoleList()
    this.getAllMenus()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('vueRole/roleList', { params: this.query })
      this.roleList = res.result.records
      this.total = res.result.total
    },
    async getAllMenus () {
      const { data: res } = await this.$http.get('vueRole/getAllMenus')
      this.allMenus = res.result
    },
    async roleMenuDialog (id) {

      this.roleId = id
      const { data: res } = await this.$http.get('vueRole/getRoleMenuById?id=' + id)
      //获取用户的菜单最下层id
      let arr = []
      res.result.items.forEach(item => {
        if (item.items.length === 0) {
          return arr.push(item.id)
        }
        item.items.forEach(i => {
          if (i.items.length === 0) {
            return arr.push(i.id)
          }

          i.items.forEach(j => {
            if (j.items.length === 0) {
              return arr.push(j.id)
            }
          })

        })
      })


      this.defaultKeys = arr
      this.roleMenuFlag = !this.roleMenuFlag
    },
    //分配权限中的确定按钮
    editUserMenus () {
      // es6语法，两个数组合并为一个
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]


      if (keys.length === 0) {
        return this.$message.error('菜单不能全空')
      }

      this.$http.post('vueRole/updateRoleMenus', this.$Qs.stringify({
        id: this.roleId,
        menuIds: keys.join(',')
      })).then(resp =>
        this.$message.success(resp.data.message))
        .catch(err => this.$message.error(err))

      this.roleMenuFlag = !this.roleMenuFlag
      this.getRoleList()

    },
    closeUserMenus () {
      this.roleMenuFlag = !this.roleMenuFlag
      // this.$refs.treeRef.setCheckedKeys([])
    },
    resetDefaultKeys () {
      this.defaultKeys = []
      this.$refs.treeRef.setCheckedKeys([])
    },

    openRoleDialog () {
      this.openRoleFlag = !this.openRoleFlag
    },
    closeRoleDialog () {
      this.$refs.addRoleFormRef.resetFields()
    },
    addRole () {
      this.$refs.addRoleFormRef.validate(async valit => {
        if (valit) {
          const { data: res } = await this.$http.post('vueRole/addRole', this.$Qs.stringify(this.addRoleForm))
          if (res.success) {
            this.$message.success(res.message)
            this.openRoleFlag = !this.openRoleFlag
          } else {
            this.$message.error(res.message)
          }

        }
      })

    },
    handleSizeChange (val) {
      this.query.size = val
      this.getRoleList()
    },
    handleCurrentChange (val) {
      this.query.current = val
      this.getRoleList()
    },
  }
}
</script>

<style scoped>

</style>
